extends Node2D

@onready var nav: NavigationAgent2D = $Player/Nav
@onready var player: CharacterBody2D = $Player
@onready var line2D: Line2D = $Line2D
@onready var tileMap: TileMap = get_node("/root/Map/TileMap")

var path := PackedVector2Array()

func _physics_process(delta: float):
	if path.is_empty():
		return
	var targetPos = getTargetPos(player.speed * delta)
	player.velocity = (targetPos - player.position).normalized() * player.speed
	var isCollided = player.move_and_slide()
	if isCollided:
		path.clear()

func getTargetPos(distance: float) -> Vector2:
	var targetPos = path[0]
	var distance_to_next = player.position.distance_to(targetPos)
	if distance > distance_to_next:
		path.remove_at(0)
		if !path.is_empty():
			return getTargetPos(distance)
	return targetPos

func _unhandled_input(event: InputEvent):
	if !(event is InputEventMouseButton) || !event.is_pressed():
		return
	if (event as InputEventMouseButton).button_index != MOUSE_BUTTON_LEFT:
		return
	var playerPosition = player.global_position
	var mousePosition = event.global_position
	var startCellPosition = tileMap.local_to_map(playerPosition)
	var endCellPosition = tileMap.local_to_map(mousePosition)
	# print(playerPosition,mousePosition,startCellPosition,endCellPosition)
	var navPath = tileMap.get_nav_path(startCellPosition, endCellPosition)
	line2D.points = navPath
	path = navPath

# func _unhandled_input(event: InputEvent):
# 	if !(event is InputEventMouseButton):
# 		return
# 	if (event as InputEventMouseButton).button_index != MOUSE_BUTTON_LEFT:
# 		return
# 	var playerPos = player.global_position
# 	var mousePos = event.global_position
# 	nav.target_location = mousePos
# 	# nav.get_next_location()
# 	line2D.set_points(nav.get_current_navigation_path())

# func _physics_process(delta):
# 	if nav.is_navigation_finished() || nav.get_final_location() == Vector2.ZERO:
# 		return
# 	var next_location = nav.get_next_location()
# 	var direction = player.global_position.direction_to(next_location)
# 	nav.set_velocity(direction * player.speed)
# 	player.velocity = direction * player.speed
# 	player.move_and_slide()
# 	print(nav.get_current_navigation_path())

# func _unhandled_input(event: InputEvent):
# 	if not event is InputEventMouseButton:
# 		return
# 	var playerPosition = player.global_position
# 	var mousePosition = event.global_position
# 	nav_2d.set_target_location(mousePosition)
# 	nav_2d.get_next_location()
# 	var navPath = nav_2d.get_nav_path()
# 	line2D.points = navPath
